package com.oschat.controller;

import com.oschat.annotation.GlobalInterceptor;
import com.oschat.entity.dto.TokenUserInfoDto;
import com.oschat.entity.dto.UserContactSearchResultDto;
import com.oschat.entity.enums.PageSize;
import com.oschat.entity.enums.ResponseCodeEnum;
import com.oschat.entity.enums.UserContactStatusEnum;
import com.oschat.entity.enums.UserContactTypeEnum;
import com.oschat.entity.po.UserContact;
import com.oschat.entity.po.UserInfo;
import com.oschat.entity.query.UserContactApplyQuery;
import com.oschat.entity.query.UserContactQuery;
import com.oschat.entity.vo.PaginationResultVO;
import com.oschat.entity.vo.ResponseVO;
import com.oschat.entity.vo.UserInfoVO;
import com.oschat.exception.BusinessException;
import com.oschat.service.UserContactApplyService;
import com.oschat.service.UserContactService;
import com.oschat.service.UserInfoService;
import com.oschat.utils.CopyTools;
import jodd.util.ArraysUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author 绿竹
 * @version 1.0
 * @description: 联系人控制层
 * @date 2025/2/11 10:03
 */
@RestController
@RequestMapping("/contact")
public class UserContactController extends ABaseController {

    @Resource
    UserContactService userContactService;
    @Resource
    UserInfoService userInfoService;
    @Resource
    UserContactApplyService userContactApplyService;

    /**
     * @description: 根据contactId搜索联系人
     * @param: request
     * contactId
     * @return: com.oschat.entity.vo.ResponseVO
     * @author 绿竹
     * @date: 2025/2/11 16:51
     */
    @RequestMapping("/search")
    @GlobalInterceptor
    public ResponseVO search(HttpServletRequest request, @NotEmpty String contactId) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        UserContactSearchResultDto resultDto = userContactService.searchContact(tokenUserInfoDto.getUserId(), contactId);
        return getSuccessResponseVO(resultDto);
    }

    /**
     * @description: 申请加好友
     * @param: request
     * contactId  目标好友的id
     * applyInfo  申请信息
     * @return: com.oschat.entity.vo.ResponseVO
     * @author Administrator
     * @date: 2025/2/11 16:55
     */
    @RequestMapping("/applyAdd")
    @GlobalInterceptor
    public ResponseVO applyAdd(HttpServletRequest request, @NotEmpty String contactId, String applyInfo) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        Integer joinType = userContactService.applyAdd(tokenUserInfoDto, contactId, applyInfo);
        return getSuccessResponseVO(joinType);
    }

    /**
     * @description: 申请聊表展示
     * @param: request
     * page
     * @return: com.oschat.entity.vo.ResponseVO
     * @author 绿竹
     * @date: 2025/2/14 9:16
     */
    @RequestMapping("/loadApply")
    @GlobalInterceptor
    public ResponseVO loadApply(HttpServletRequest request, Integer page) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);

        UserContactApplyQuery applyQuery = new UserContactApplyQuery();
        applyQuery.setOrderBy("last_apply_time desc");
        applyQuery.setReceiveUserId(tokenUserInfoDto.getUserId());
        applyQuery.setPageNo(page);
        applyQuery.setPageSize(PageSize.SIZE15.getSize());
        applyQuery.setQueryContactInfo(true);
        PaginationResultVO resultVO = userContactApplyService.findListByPage(applyQuery);
        return getSuccessResponseVO(resultVO);
    }

    /**
     * @description: 处理申请
     * @param: request
     * applyId  申请id
     * status  处理状态
     * @return: com.oschat.entity.vo.ResponseVO
     * @author 绿竹
     * @date: 2025/4/3
     */
    @RequestMapping("/dealWithApply")
    @GlobalInterceptor
    public ResponseVO dealWithApply(HttpServletRequest request, Integer applyId, Integer status) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        String userId = tokenUserInfoDto.getUserId();
        userContactApplyService.dealWithApply(userId, applyId, status);
        return getSuccessResponseVO(null);
    }

    /**
     * @description: 加载联系人
     * @param: request
     * contactType  联系人类型
     * @return: com.oschat.entity.vo.ResponseVO
     * @author 绿竹
     * @date: 2025/4/3
     * <p>
     * 我账号登录之后加载联系人，是我个人所有联系人的
     */
    @RequestMapping("/loadContact")
    @GlobalInterceptor
    public ResponseVO loadContact(HttpServletRequest request, @NotNull String contactType) {
        UserContactTypeEnum contactTypeEnum = UserContactTypeEnum.getByName(contactType);
        if (null == contactTypeEnum) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        UserContactQuery contactQuery = new UserContactQuery();
        contactQuery.setUserId(tokenUserInfoDto.getUserId());
        contactQuery.setContactType(contactTypeEnum.getType());
        if (contactTypeEnum.USER == contactTypeEnum) {
            contactQuery.setQueryContactUserInfo(true);
        } else if (contactTypeEnum.GROUP == contactTypeEnum) {
            contactQuery.setQueryGroupInfo(true);
            contactQuery.setExcludeMyGroup(true);
        }
        contactQuery.setOrderBy("last_update_time desc");
        contactQuery.setStatusArray(new Integer[]{
                UserContactStatusEnum.FRIEND.getStatus(),
                UserContactStatusEnum.DEL_BE.getStatus(),
                UserContactStatusEnum.BLACKLIST_BE.getStatus(),});
        List<UserContact> contactList = userContactService.findListByParam(contactQuery);
        return getSuccessResponseVO(contactList);
    }


    /***
     * @description: 获取联系人的信息（不一定是好友）
     * @author Administrator
     * @date 2025/7/19 20:00
     * @version 1.0
     *
     * 为联系人的话，意味着已经添加为好友，传入的是contactId，通过contactId先去联系人表查询联系人的关系，
     * 如果查询不到信息报错，status判断状态，然后再去查询用户信息表
     *
     */
    @RequestMapping("/getContactInfo")
    @GlobalInterceptor
    public ResponseVO getContactInfo(HttpServletRequest request, @NotNull String contactId) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        UserInfo userInfo = userInfoService.getUserInfoByUserId(contactId);
        UserInfoVO userInfoVO = CopyTools.copy(userInfo, UserInfoVO.class);
        userInfoVO.setContactStatus(UserContactStatusEnum.NOT_FRIEND.getStatus());
        UserContact userContact = userContactService.getUserContactByUserIdAndContactId(tokenUserInfoDto.getUserId(), contactId);
        if (userContact != null) {
            userInfoVO.setContactStatus(UserContactStatusEnum.FRIEND.getStatus());
        }
        return getSuccessResponseVO(userInfoVO);
    }


    /**
     * @description: 获取联系人信息（一定是好友）
     * @author Administrator
     * @date 2025/7/31 14:19
     * @version 1.0
     */
    @RequestMapping("/getContactUserInfo")
    @GlobalInterceptor
    public ResponseVO getContactUserInfo(HttpServletRequest request, @NotNull String contactId) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);

        UserContact userContact = userContactService.getUserContactByUserIdAndContactId(tokenUserInfoDto.getUserId(), contactId);
        if (null == userContact || !ArraysUtil.contains(new Integer[]{
                UserContactStatusEnum.FRIEND.getStatus(),
                UserContactStatusEnum.DEL_BE.getStatus(),
                UserContactStatusEnum.BLACKLIST_BE.getStatus()
        },userContact.getStatus())) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        UserInfo userInfo = userInfoService.getUserInfoByUserId(contactId);
        UserInfoVO userInfoVO = CopyTools.copy(userInfo, UserInfoVO.class);
        return getSuccessResponseVO(userInfoVO);
    }

    /**
     * @description: 删除联系人
     * @author Administrator
     * @date 2025/7/31 15:32
     * @version 1.0
     *
     * 删除联系人，需要把把联系人的状态值为被我删除，那么传入的是contactId，
     * 我需要先去判断这个联系人是否存在，没有则报错，再判断与联系人的关系，只有为好友状态才做删除
     * 然后我还需要将我与好友的联系人状态全都给改了
     *
     *
     */
    @RequestMapping("/delContact")
    @GlobalInterceptor
    public ResponseVO delContact(HttpServletRequest request, @NotNull String contactId) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
         userContactService.removeUserContact(tokenUserInfoDto.getUserId(),contactId,UserContactStatusEnum.DEL);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/addContact2BlackList")
    @GlobalInterceptor
    public ResponseVO addContact2BlackList(HttpServletRequest request, @NotNull String contactId) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        userContactService.removeUserContact(tokenUserInfoDto.getUserId(),contactId,UserContactStatusEnum.BLACKLIST);
        return getSuccessResponseVO(null);
    }
}
